package com.zhe.zheblogmaster.config;

import com.zhe.zheblogmaster.util.JacksonUtil;
import com.zhe.zheblogmaster.util.ResultBody;
import com.zhe.zheblogmaster.util.ZheBlogUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常解析类
 *
 * @author WHAOU
 * @date 2021/9/2
 * @email whaou@qq.com
 */
@ControllerAdvice
public class ExceptionResolver {
    @ExceptionHandler(Exception.class)
    public ModelAndView doException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String viewName = "/error/5xx.html";
        return parsingExceptions(e, request, response, viewName);
    }

    private ModelAndView parsingExceptions(Exception e, HttpServletRequest request, HttpServletResponse response, String viewName) throws IOException {
        String msg = e.getClass() + ":" + e.getMessage();
        Boolean isAjax = ZheBlogUtils.isAjax(request);
        if (isAjax) {
            ResultBody<Object> error = ResultBody.error(msg);
            String jsonStr = JacksonUtil.toJson(error);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonStr);
            return null;
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject(BlogConstants.EXCEPTION_MESSAGE, msg);
            modelAndView.setViewName(viewName);
            return modelAndView;
        }
    }
}
